package org.jeecg.modules.demo.ch.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ch.Utils.OrderBomUtils;
import org.jeecg.modules.demo.ch.common.BigDecimalUtil;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.*;
import org.jeecg.modules.demo.ch.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

 /**
 * @Description: 订购BOM
 * @Author: jeecg-boot
 * @Date:   2022-09-15
 * @Version: V1.0
 */
@Api(tags="订购BOM")
@RestController
@RequestMapping("/ch/chOrderBom")
@Slf4j
public class ChOrderBomController extends JeecgController<ChOrderBom, IChOrderBomService> {

	@Autowired
	private IChOrderBomService chOrderBomService;

	 @Autowired
	 private IChDesignBomMasterService iChDesignBomMasterService;

	 @Autowired
	 private IChMaterialCodeRawMaterialService iChMaterialCodeRawMaterialService; //物料编码原材料类表

	 @Autowired
	 private IChRawMaterialCodeComparisonService iChRawMaterialCodeComparisonService;//原材料代码对照表

	 @Autowired
	 private IChMaterialCodeAccessoriesService iChMaterialCodeAccessoriesService; //物料编码配件类表

	 @Autowired
	 private IChPartsCodeComparisonService iChPartsCodeComparisonService; //配件代码对照表

	 @Autowired
	 private IChAllowanceService iChAllowanceService; //余量规则表

	 @Autowired
	 private IChParameterService iChParameterService; //系统参数表


	 /**
	  *  查询现有的版本集合
	  * @param
	  * @return
	  */
	 @AutoLog(value = "订购BOM-查询现有的版本集合")
	 @ApiOperation(value="订购BOM-查询现有的版本集合", notes="订购BOM-查询现有的版本集合")
	 @GetMapping(value = "/queryVersions")
	 public Result<List<String>> queryVersions(ChOrderBom chOrderBom) {
		 String moldCode = chOrderBom.getMoldCode();	//根据模具编号获取id
		 moldCode="ch2022019D";
		 if (!StringUtils.hasLength(moldCode)){
			 return Result.error("传来的模具编码不能为空!");
		 }
		 LambdaQueryWrapper<ChDesignBomMaster> chDesignBomMasterLambdaQueryWrapper = new QueryWrapper<ChDesignBomMaster>().lambda();
		 chDesignBomMasterLambdaQueryWrapper.eq(ChDesignBomMaster::getMoldCode,moldCode);
		 ChDesignBomMaster one = iChDesignBomMasterService.getOne(chDesignBomMasterLambdaQueryWrapper);
		 if (one == null){
			 return Result.error("根据模具编号:"+moldCode+"未查询到数据!");
		 }

		 //从ChOrderBom查询数据列表
		 String	chDesignBomMasterId =one.getId();

		 //根据模具设计BOM主表id获取最新的版本
		 QueryWrapper<ChOrderBom> chOrderBomQueryWrapper = new QueryWrapper<>();
		 chOrderBomQueryWrapper.select("DISTINCT version as version");
		 chOrderBomQueryWrapper.eq("ch_design_bom_master_id",chDesignBomMasterId);
		 List<ChOrderBom> list = chOrderBomService.list(chOrderBomQueryWrapper);

		 if (list == null || list.size() == 0){
			 return Result.error("根据模具主表id:"+moldCode+"未查询到最新的版本数据!");
		 }
		 //封装版本
		 ArrayList<String> arrayList = new ArrayList<>();
		 for (ChOrderBom orderBom : list) {
			 arrayList.add(CommonMst.ORDER_BOM.V+orderBom.getVersion());
		 }
		 return Result.ok(arrayList);
	 }


	/**
	 * 分页列表查询
	 *
	 * @param chOrderBom
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "订购BOM-分页列表查询")
	@ApiOperation(value="订购BOM-分页列表查询", notes="订购BOM-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ChOrderBom>> queryPageList(ChOrderBom chOrderBom,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		log.info("传过来的参数：chOrderBom:{},pageNo:{},pageSize:{}",chOrderBom,pageNo,pageSize);

		long startTime = System.currentTimeMillis();
		String moldCode = chOrderBom.getMoldCode();	//根据模具编号获取id
	//	moldCode="ch2022019D";
		LambdaQueryWrapper<ChDesignBomMaster> chDesignBomMasterLambdaQueryWrapper = new QueryWrapper<ChDesignBomMaster>().lambda();
		chDesignBomMasterLambdaQueryWrapper.eq(ChDesignBomMaster::getMoldCode,moldCode);
		ChDesignBomMaster one = iChDesignBomMasterService.getOne(chDesignBomMasterLambdaQueryWrapper);
		if (one == null){
			return Result.error("根据模具编号:"+moldCode+"未查询到数据!");
		}

		//更新设计BOM中的表数据
//		List<ChDesignBomDetail> list = iChDesignBomDetailService.list();
//		ArrayList<ChOrderBom> chOrderBoms = new ArrayList<>();
//		for (ChDesignBomDetail chDesignBomDetail : list) {
//			ChOrderBom chOrderBom1 = new ChOrderBom();
//			if (null != chDesignBomDetail.getSerialNumber()){
//				chOrderBom1.setDesignSerialNo(chDesignBomDetail.getSerialNumber().toString());
//			}
//			BeanUtils.copyProperties(chDesignBomDetail,chOrderBom1);
//			chOrderBoms.add(chOrderBom1);
//		}
//		chOrderBomService.saveOrUpdateBatch(chOrderBoms);

		//从ChOrderBom查询数据列表
		String	chDesignBomMasterId =one.getId();

		//根据模具设计BOM主表id获取最新的版本
		QueryWrapper<ChOrderBom> chOrderBomQueryWrapper = new QueryWrapper<>();
		chOrderBomQueryWrapper.select("MAX(version) as version");
		chOrderBomQueryWrapper.eq("ch_design_bom_master_id",chDesignBomMasterId);
		ChOrderBom bomServiceOne = chOrderBomService.getOne(chOrderBomQueryWrapper);
		if (bomServiceOne == null){
			return Result.error("根据模具主表id:"+moldCode+"未查询到最新的版本数据!");
		}
		String material = chOrderBom.getMaterial();//获取材料
		String version = chOrderBom.getVersion();//获取版本

		LambdaQueryWrapper<ChOrderBom> chOrderBomLambdaQueryWrapper = new QueryWrapper<ChOrderBom>().lambda();
		chOrderBomLambdaQueryWrapper.eq(ChOrderBom::getChDesignBomMasterId,chDesignBomMasterId);//根据主表id查询附属表
		if (StringUtils.hasLength(version)){ //传来的版本不为空
			if (version.contains(CommonMst.ORDER_BOM.V)){
				version = version.replace(CommonMst.ORDER_BOM.V, "");
			}
			chOrderBomLambdaQueryWrapper.eq(ChOrderBom::getVersion,version);
		}else {//为空查询默认的
			chOrderBomLambdaQueryWrapper.eq(ChOrderBom::getVersion,bomServiceOne.getVersion());
		}

		chOrderBomLambdaQueryWrapper.eq(ChOrderBom::getIsDelete,0); //获取正常数据
		Integer transferBenefitModelStatus = chOrderBom.getTransferBenefitModelStatus();//转益模的状态（1.未转2.已转）
		chOrderBomLambdaQueryWrapper.eq(StringUtils.hasLength(material) && material.equals("STD"),ChOrderBom::getMaterial,material);

		chOrderBomLambdaQueryWrapper.ne(StringUtils.hasLength(material) && material.equals("非STD"),ChOrderBom::getMaterial,"STD");
		chOrderBomLambdaQueryWrapper.eq(null != transferBenefitModelStatus,ChOrderBom::getTransferBenefitModelStatus,transferBenefitModelStatus);
		chOrderBomLambdaQueryWrapper.orderByAsc(ChOrderBom::getSerialNumber);

		Page<ChOrderBom> page = new Page<>(pageNo, pageSize);
		IPage<ChOrderBom> pageInfo = chOrderBomService.page(page, chOrderBomLambdaQueryWrapper);
		log.info("访问时间为："+(System.currentTimeMillis()-startTime));
		return Result.OK(pageInfo);
	}


	/**
	 *   添加
	 *
	 * @param chOrderBom
	 * @return
	 */
	@AutoLog(value = "订购BOM-添加")
	@ApiOperation(value="订购BOM-添加", notes="订购BOM-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:ch_order_bom:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ChOrderBom chOrderBom) {
		String moldCode = chOrderBom.getMoldCode();
		moldCode="ch2022019D";
		if (!StringUtils.hasLength(moldCode)){
			return Result.error("模具编码不能为空!");
		}
		log.info("传过来的参数chOrderBom:{}moldCode:{}",chOrderBom,moldCode);
		//新增
		LambdaQueryWrapper<ChDesignBomMaster> chDesignBomMasterLambdaQueryWrapper = new QueryWrapper<ChDesignBomMaster>().lambda();
		chDesignBomMasterLambdaQueryWrapper.eq(ChDesignBomMaster::getMoldCode,moldCode);
		ChDesignBomMaster chDesignBomMaster = iChDesignBomMasterService.getOne(chDesignBomMasterLambdaQueryWrapper);
		if (chDesignBomMaster == null){
			return Result.error("输入的模具编码有误,请核查!根据模具编码模具编码未查询到数据!");
		}
		chOrderBom.setChDesignBomMasterId(chDesignBomMaster.getId());//赋值模具编码id
		chOrderBom.setVersion(CommonMst.ORDER_BOM.INIT_VERSION);
		String serialNum = setOrderBomSerialNum(chOrderBom);
		chOrderBomService.save(chOrderBom);
		setOrderBomSerialNumAddOne(chOrderBom,serialNum);

//		if (StringUtils.hasLength(chOrderBom.getId())){//id不为空进行修改
//			chOrderBomService.updateById(chOrderBom);
//		}else {//新增
//
//		}
		return Result.OK("添加成功！");
	}

	 /**
	  * 初始化查询并赋值订购BOM序列号
	  * @param chOrderBom
	  */
	public String setOrderBomSerialNum(ChOrderBom chOrderBom){
		LambdaQueryWrapper<ChParameter> chParameterLambdaQueryWrapper = new QueryWrapper<ChParameter>().lambda();
		chParameterLambdaQueryWrapper.eq(ChParameter::getMajorCategories,CommonMst.ORDER_BOM.ORDER_BOM);
		chParameterLambdaQueryWrapper.eq(ChParameter::getLittleClass,CommonMst.ORDER_BOM.ORDER_BOM_SERIAL_NUMBER);
		ChParameter chParameter = iChParameterService.getOne(chParameterLambdaQueryWrapper);
		if (chParameter == null){
			throw  new RuntimeException("新增异常!根据大类小类查询订购BOM序列号的值异常!");
		}
		LambdaQueryWrapper<ChParameter> chParameterLambdaQueryWrapperTwo = new QueryWrapper<ChParameter>().lambda();
		chParameterLambdaQueryWrapperTwo.eq(ChParameter::getMajorCategories,CommonMst.ORDER_BOM.ORDER_BOM);
		chParameterLambdaQueryWrapperTwo.eq(ChParameter::getLittleClass,CommonMst.ORDER_BOM.DESIGN_BOM_SERIAL_NUMBER);
		ChParameter chParameter1 = iChParameterService.getOne(chParameterLambdaQueryWrapperTwo);
		if (chParameter1 == null){
			throw  new RuntimeException("新增异常!根据大类小类查询设计BOM序列号的值异常!");
		}
		//获取自增的订购BOM序列号，设计BOM序列号
		chOrderBom.setDesignSerialNo(CommonMst.ORDER_BOM.A+chParameter.getValueStr());//订购BOM序列号 A01
		chOrderBom.setSerialNumber(Integer.parseInt(chParameter1.getValueStr()));//设计BOM序列号  10000开始
		return chParameter.getValueStr();
	}

	 /**
	  * 订购BOM序列号和设计BOM序号+1
	  * @param chOrderBom
	  */
	 public void setOrderBomSerialNumAddOne(ChOrderBom chOrderBom,String  orderBomSerialNo){
		 LambdaUpdateWrapper<ChParameter> chParameterLambdaUpdateWrapper = new UpdateWrapper<ChParameter>().lambda();
		 chParameterLambdaUpdateWrapper.eq(ChParameter::getMajorCategories,CommonMst.ORDER_BOM.ORDER_BOM);
		 chParameterLambdaUpdateWrapper.eq(ChParameter::getLittleClass,CommonMst.ORDER_BOM.ORDER_BOM_SERIAL_NUMBER);
		 chParameterLambdaUpdateWrapper.set(ChParameter::getValueStr,Integer.parseInt(orderBomSerialNo)+1);
		 iChParameterService.update(chParameterLambdaUpdateWrapper);

		 Integer serialNumber = chOrderBom.getSerialNumber();//设计BOM序列号
		 LambdaUpdateWrapper<ChParameter> chParameterLambdaUpdateWrapperTwo = new UpdateWrapper<ChParameter>().lambda();
		 chParameterLambdaUpdateWrapperTwo.eq(ChParameter::getMajorCategories,CommonMst.ORDER_BOM.ORDER_BOM);
		 chParameterLambdaUpdateWrapperTwo.eq(ChParameter::getLittleClass,CommonMst.ORDER_BOM.DESIGN_BOM_SERIAL_NUMBER);
		 chParameterLambdaUpdateWrapperTwo.set(ChParameter::getValueStr,serialNumber+1);
		 iChParameterService.update(chParameterLambdaUpdateWrapperTwo);
	 }

	/**
	 *  编辑
	 *
	 * @param chOrderBom
	 * @return
	 */
	@AutoLog(value = "订购BOM-编辑")
	@ApiOperation(value="订购BOM-编辑", notes="订购BOM-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:ch_order_bom:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ChOrderBom chOrderBom) {
		log.info("传过来的参数chOrderBom:{}",chOrderBom);
		String withoutAllowanceDimension1 = chOrderBom.getWithoutAllowanceDimension();//未加余量尺寸
		//将未加余量尺寸 包含的x替换为X
		if (StringUtils.hasLength(withoutAllowanceDimension1)){
			withoutAllowanceDimension1=withoutAllowanceDimension1.replace(CommonMst.Data_Division_Constant.Little_Division_Constant, CommonMst.Data_Division_Constant.Division_Constant);
			chOrderBom.setWithoutAllowanceDimension(withoutAllowanceDimension1);
		}
		//tip1:原材料以及为空的逻辑 赋值料件编码和料件名称
		chOrderBom.setMaterialCode("");//料件编码
		chOrderBom.setMaterialName("");//料件名称

		chOrderBom.setSpecifications("");//规格
		chOrderBom.setSpecificationsDescription("");//规格说明
		chOrderBom.setSoftAndHardMaterials("");//软硬料
		chOrderBom.setFineWool("");//精毛料

		String fineWool = "";//精毛料
		String softAndHardMaterials = "";//软硬料
		String bulkPartsType = chOrderBom.getBulkPartsType();//散件类型
		//初始化更新
		if (!StringUtils.hasLength(chOrderBom.getErpCode())){
			chOrderBomService.saveOrUpdate(chOrderBom);
			return Result.OK("相关数据已清除！");
		}
		if (!StringUtils.hasLength(bulkPartsType)){//为空时赋值 空
			bulkPartsType = CommonMst.ORDER_BOM.EMPTY;
		}
		if (!StringUtils.hasLength(chOrderBom.getRawMaterialsAndAccessories()) || CommonMst.ORDER_BOM.RAW_MATERIAL.equals(chOrderBom.getRawMaterialsAndAccessories())){//  原材料
			//根据erp代码的代码转大写查找原材料对照表中的料件编码
			LambdaQueryWrapper<ChRawMaterialCodeComparison> ChRawMaterialCodeComparisonWrapper = new QueryWrapper<ChRawMaterialCodeComparison>().lambda();
			if (StringUtils.hasLength(chOrderBom.getErpCode())){
				ChRawMaterialCodeComparisonWrapper.eq(StringUtils.hasLength(chOrderBom.getErpCode()),ChRawMaterialCodeComparison::getErpCode,chOrderBom.getErpCode().toUpperCase());
			}
			List<ChRawMaterialCodeComparison> chRawMaterialCodeComparisonList = iChRawMaterialCodeComparisonService.list(ChRawMaterialCodeComparisonWrapper);
			if (chRawMaterialCodeComparisonList.isEmpty() || chRawMaterialCodeComparisonList.size() == 0){
				log.error("ERP代码有误,请检查！根据erp代码在原材料对照表中未找到对应的物料编码原材料表id!");
				return Result.custom_Error("ERP代码有误,请检查！根据erp代码在原材料对照表中未找到对应的物料编码原材料表id!");
			}
			String chMaterialCodeRawMaterialId = chRawMaterialCodeComparisonList.get(0).getChMaterialCodeRawMaterialId();//物料编码原材料类表id
			//根据物料编码原材料表id查找料件编码
			LambdaQueryWrapper<ChMaterialCodeRawMaterial> chMaterialCodeRawMaterialLambdaQueryWrapper = new QueryWrapper<ChMaterialCodeRawMaterial>().lambda();
			chMaterialCodeRawMaterialLambdaQueryWrapper.eq(ChMaterialCodeRawMaterial::getId,chMaterialCodeRawMaterialId);
			List<ChMaterialCodeRawMaterial> chMaterialCodeRawMaterialList = iChMaterialCodeRawMaterialService.list(chMaterialCodeRawMaterialLambdaQueryWrapper);
			if (chMaterialCodeRawMaterialList.isEmpty() || chMaterialCodeRawMaterialList.size() == 0){
				log.error("ERP代码有误,请检查！根据物料编码原材料类表id查找数据为空!");
				return Result.custom_Error("ERP代码有误,请检查！根据物料编码原材料类表id查找数据为空!");
			}
			chOrderBom.setMaterialCode(OrderBomUtils.setStringIfNotNull(chMaterialCodeRawMaterialList.get(0).getItemCode()));//料件编码
			chOrderBom.setMaterialName(OrderBomUtils.setStringIfNotNull(chMaterialCodeRawMaterialList.get(0).getItemName()));//料件名称
			chOrderBom.setT100Units(OrderBomUtils.setStringIfNotNull(chMaterialCodeRawMaterialList.get(0).getUnit()));//设置单位
			softAndHardMaterials=chMaterialCodeRawMaterialList.get(0).getSoftAndHardMaterials();
			fineWool=chMaterialCodeRawMaterialList.get(0).getFineWool();
			chOrderBom.setSoftAndHardMaterials(OrderBomUtils.setStringIfNotNull(softAndHardMaterials));//软硬料
			chOrderBom.setFineWool(OrderBomUtils.setStringIfNotNull(fineWool));//精毛料

			//2.原材料情况下 订料和不订料的逻辑  赋值规格和规格说明
			String mixMaterialsAndNotOrder = chOrderBom.getMixMaterialsAndNotOrder();//拼料和不订料
			String withoutAllowanceDimension = chOrderBom.getWithoutAllowanceDimension();//未加余量的尺寸
		//	withoutAllowanceDimension = OrderBomUtils.eliminateRedundantZeros(withoutAllowanceDimension);//去除多余的零
			if (StringUtils.hasLength(mixMaterialsAndNotOrder) && CommonMst.ORDER_BOM.SPLICING.equals(mixMaterialsAndNotOrder)){//拼料的情况下
				if (StringUtils.hasLength(withoutAllowanceDimension)){
					chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
					chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
				}
			}else if (StringUtils.hasLength(mixMaterialsAndNotOrder) && CommonMst.ORDER_BOM.NO_ORDER.equals(mixMaterialsAndNotOrder)){//不订料的情况下
				if (StringUtils.hasLength(withoutAllowanceDimension)){
					chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
					chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
				}
			}else if (!StringUtils.hasLength(mixMaterialsAndNotOrder)){//为空的情况下
				//3.原材料以及为空的逻辑 是圆料还是方料的情况 赋值规格和规格说明  未加余量尺寸首字母是数字为圆料，其他为方料
				//判断首字母是否为数字
				Boolean aBoolean = OrderBomUtils.FirstCharIsNumber(withoutAllowanceDimension);
				if (!aBoolean){//圆料
					chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
					chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
				}else {//方料
					//获取精毛料
					if (StringUtils.hasLength(fineWool) && CommonMst.ORDER_BOM.CONCENTRATE.equals(fineWool)){//精料
						//精料的情况下判断软硬料 加余量 以及 公差
						if (StringUtils.hasLength(softAndHardMaterials) && CommonMst.ORDER_BOM.HARD_MATERIAL.equals(softAndHardMaterials)){//硬料
							addMarginAccordingToSize(CommonMst.ORDER_BOM.HARD_MATERIAL, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType, withoutAllowanceDimension,chOrderBom);
							sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.HARD_MATERIAL, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType,chOrderBom);

						}else if (StringUtils.hasLength(softAndHardMaterials) && CommonMst.ORDER_BOM.HARD_MATERIAL2.equals(softAndHardMaterials)){//硬料2
							addMarginAccordingToSize(CommonMst.ORDER_BOM.HARD_MATERIAL2, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType, withoutAllowanceDimension,chOrderBom);
							sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.HARD_MATERIAL2, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType,chOrderBom);

						}else if (StringUtils.hasLength(softAndHardMaterials) && CommonMst.ORDER_BOM.SOFT_MATERIAL.equals(softAndHardMaterials)){//软料
							addMarginAccordingToSize(CommonMst.ORDER_BOM.SOFT_MATERIAL, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType, withoutAllowanceDimension,chOrderBom);
							sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.SOFT_MATERIAL, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType,chOrderBom);

						}else if (StringUtils.hasLength(softAndHardMaterials) && CommonMst.ORDER_BOM.SOFT_MATERIAL2.equals(softAndHardMaterials)){//软料2
							addMarginAccordingToSize(CommonMst.ORDER_BOM.SOFT_MATERIAL2, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType, withoutAllowanceDimension,chOrderBom);
							sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.SOFT_MATERIAL2, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType,chOrderBom);

						}else {
							log.info("传过来的参数软硬料softAndHardMaterials:{}暂不做处理!",softAndHardMaterials);
						}

					}else if (StringUtils.hasLength(fineWool) && CommonMst.ORDER_BOM.WOOL.equals(fineWool)){//毛料
						chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
						chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
					}else if (StringUtils.hasLength(fineWool) && CommonMst.ORDER_BOM.WOOL2.equals(fineWool)){//毛料2
						//规格和规格说明  赋值时  加二有小数点就进一
						withoutAllowanceDimension = OrderBomUtils.DataRoundedUp(withoutAllowanceDimension);
						chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
						chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
						sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.NOTHING, CommonMst.ORDER_BOM.PARTS_TYP, CommonMst.ORDER_BOM.EMPTY,chOrderBom);

					}else if (StringUtils.hasLength(fineWool) && CommonMst.ORDER_BOM.NOTHING.equals(fineWool)){//无
						chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
						chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
					}else {
						log.info("传过来的精毛料fineWool:{}暂不做处理!",fineWool);
					}
				}
			}else {
				log.error("传过来的拼料和不订料mixMaterialsAndNotOrder:{}暂不做处理",mixMaterialsAndNotOrder);
				return Result.custom_Error("传过来的拼料和不订料mixMaterialsAndNotOrder:{}暂不做处理"+mixMaterialsAndNotOrder);
			}


			//tip2:配件逻辑
		}else if (StringUtils.hasLength(chOrderBom.getRawMaterialsAndAccessories()) && CommonMst.ORDER_BOM.PARTS.equals(chOrderBom.getRawMaterialsAndAccessories())){//配件
			//根据erp代码的代码转大写查找配件类对照表中的料件编码
			LambdaQueryWrapper<ChPartsCodeComparison> chPartsCodeComparisonLambdaQueryWrapper = new QueryWrapper<ChPartsCodeComparison>().lambda();
			chPartsCodeComparisonLambdaQueryWrapper.eq(ChPartsCodeComparison::getErpCode,chOrderBom.getErpCode().toUpperCase());
			List<ChPartsCodeComparison> chPartsCodeComparisonList  = iChPartsCodeComparisonService.list(chPartsCodeComparisonLambdaQueryWrapper);
			if (chPartsCodeComparisonList.isEmpty() || chPartsCodeComparisonList.size() == 0){
				log.error("ERP代码有误,请检查！根据erp代码在配件代码对照表中未找到对应的物料编码配件类表id!");
				return Result.custom_Error("ERP代码有误,请检查！根据erp代码在配件代码对照表中未找到对应的物料编码配件类表id!");
			}
			String chMaterialCodeRawMaterialId = chPartsCodeComparisonList.get(0).getChMaterialCodeAccessoriesId();//物料编码配件类表id
			//根据物料编码配件类表id查找料件编码暂存
			LambdaQueryWrapper<ChMaterialCodeAccessories> chMaterialCodeAccessoriesLambdaQueryWrapper = new QueryWrapper<ChMaterialCodeAccessories>().lambda();
			chMaterialCodeAccessoriesLambdaQueryWrapper.eq(ChMaterialCodeAccessories::getId,chMaterialCodeRawMaterialId);
			List<ChMaterialCodeAccessories> chMaterialCodeAccessoriesList = iChMaterialCodeAccessoriesService.list(chMaterialCodeAccessoriesLambdaQueryWrapper);
			if (chMaterialCodeAccessoriesList.isEmpty() || chMaterialCodeAccessoriesList.size() == 0){
				log.error("ERP代码有误,请检查！根据物料编码配件类表id查找数据为空!");
				return Result.custom_Error("ERP代码有误,请检查！根据物料编码配件类表id查找数据为空!");
			}
			String itemCode = chMaterialCodeAccessoriesList.get(0).getItemCode();//暂存
			String itemName = chMaterialCodeAccessoriesList.get(0).getItemName();//暂存
			String unit = chMaterialCodeAccessoriesList.get(0).getUnit();//暂存

			//根据订购BPM版面中的ERP代码+未加余量的尺寸精确匹配配件代码对照表中的ERP代码.
			String erpCode = chOrderBom.getErpCode();
			String withoutAllowanceDimension = chOrderBom.getWithoutAllowanceDimension();
			if (StringUtils.hasLength(withoutAllowanceDimension)){
				erpCode = erpCode+withoutAllowanceDimension;
			}
			//根据erp代码的代码转大写查找配件类对照表中的料件编码
			LambdaQueryWrapper<ChPartsCodeComparison> chPartsCodeComparisonLambdaQueryWrapperTwo = new QueryWrapper<ChPartsCodeComparison>().lambda();
			chPartsCodeComparisonLambdaQueryWrapperTwo.eq(ChPartsCodeComparison::getErpCode,erpCode.toUpperCase());
			List<ChPartsCodeComparison> chPartsCodeComparisons  = iChPartsCodeComparisonService.list(chPartsCodeComparisonLambdaQueryWrapperTwo);
			if (chPartsCodeComparisons.isEmpty() || chPartsCodeComparisons.size() == 0){ //查询为空
				//将初始的料件编码赋值到订购BOM中料件编码栏位中
				chOrderBom.setMaterialCode(itemCode);
				chOrderBom.setMaterialName(itemName);
				chOrderBom.setT100Units(unit);
			}else {
				String chMaterialCodeAccessoriesId = chPartsCodeComparisons.get(0).getChMaterialCodeAccessoriesId();//物料编码配件类表id
				LambdaQueryWrapper<ChMaterialCodeAccessories> chMaterialCodeAccessoriesLambdaQueryWrapperTwo = new QueryWrapper<ChMaterialCodeAccessories>().lambda();
				chMaterialCodeAccessoriesLambdaQueryWrapperTwo.eq(ChMaterialCodeAccessories::getId,chMaterialCodeAccessoriesId);
				List<ChMaterialCodeAccessories> chMaterialCodeAccessories = iChMaterialCodeAccessoriesService.list(chMaterialCodeAccessoriesLambdaQueryWrapperTwo);
				if (chMaterialCodeAccessories.isEmpty() || chMaterialCodeAccessories.size() == 0){
					log.error("ERP代码有误,请检查！根据物料编码配件类表id查找数据为空!");
					return Result.custom_Error("ERP代码有误,请检查！根据物料编码配件类表id查找数据为空!");
				}
				itemCode = chMaterialCodeAccessories.get(0).getItemCode();//暂存
				chOrderBom.setMaterialCode(OrderBomUtils.setStringIfNotNull(itemCode));
				chOrderBom.setMaterialName(OrderBomUtils.setStringIfNotNull(chMaterialCodeAccessories.get(0).getItemName()));
				chOrderBom.setT100Units(OrderBomUtils.setStringIfNotNull(chMaterialCodeAccessories.get(0).getUnit()));
			}
			chOrderBom.setSpecifications(OrderBomUtils.setStringIfNotNull(withoutAllowanceDimension));//配件类的直接赋值未加余量尺寸
			chOrderBom.setSpecificationsDescription(OrderBomUtils.setStringIfNotNull(withoutAllowanceDimension));//配件类的直接赋值未加余量尺寸
		}else {
			//传来的原材料及配件是
			String rawMaterialsAndAccessories = chOrderBom.getRawMaterialsAndAccessories();
			return Result.custom_Error("传来的原材料及配件rawMaterialsAndAccessories:{}暂不做处理!"+rawMaterialsAndAccessories);
		}
		log.info("匹配到的料件编码itemCode:{},itemName料件名称:{}",chOrderBom.getMaterialCode(),chOrderBom.getMaterialName());
		//chOrderBomService.updateById(chOrderBom);
		//获取重量
		String weight = getWeight(chOrderBom);
		chOrderBom.setWeight(weight);
		//设置是否是库存标准件
		String isStandardPart = getIsStandardPart(chOrderBom);
		chOrderBom.setIsStandardPart(isStandardPart);
		chOrderBomService.saveOrUpdate(chOrderBom);
		return Result.OK("编辑成功!");
	}

	 /**
	  * 获取是否是库存标准件
	  * 料件编码前两位是61或者63  后3位不是001 是库存标准件 其余情况都是否
	  * @param chOrderBom
	  * @return
	  */
	 private  String getIsStandardPart(ChOrderBom chOrderBom) {
		 String flag =CommonMst.ORDER_BOM.Not_STANDARD_PART;
		 String materialCode = chOrderBom.getMaterialCode();//料件编码
		 if (!StringUtils.hasLength(materialCode)){
			 return flag;
		 }
		 if (materialCode.length()<3){
			 return flag;
		 }
		 String firstTwo = materialCode.substring(0, 2);
		 String lastThree = materialCode.substring(materialCode.length() - 3);

		 //料件编码前两位是61或者63  后3位不是001 是库存标准件 其余情况都是否
		 if ((firstTwo.equals(CommonMst.ORDER_BOM.STANDARD_PART_BASIS1) || firstTwo.equals(CommonMst.ORDER_BOM.STANDARD_PART_BASIS2)) && !lastThree.equals(CommonMst.ORDER_BOM.STANDARD_PART_BASIS3) ){
			 flag =CommonMst.ORDER_BOM.IS_STANDARD_PART;
		 }
		 log.info("firstTwo:{},lastThree:{},isStandardPart:{}",firstTwo,lastThree,flag);
		return flag;
	 }






	 /**
	  * 获取重量
	  * @return
	  */
	public String getWeight(ChOrderBom chOrderBom){
		String weight="";
		String t100Units = chOrderBom.getT100Units();//T100单位
		String materialCode = chOrderBom.getMaterialCode();//物料编码
		if (!StringUtils.hasLength(t100Units)){
			return "";
		}
		if (!t100Units.equals(CommonMst.ORDER_BOM.UNIT)){
			return "";
		}
		//重量只计算单位为KG的
		//根据规格判断是方料还是圆料（方料：两个X 长*宽*高*密度/1000000000）   获取规格
		//方料（圆料  1个X 3.14*（直径/2）*(直径/2) * 长度 * 密度/1000000000）  Φ160X15
		String specifications = chOrderBom.getSpecifications();
		if (!StringUtils.hasLength(specifications)){
			return "";
		}
		if (!specifications.contains(CommonMst.Data_Division_Constant.Division_Constant)){
			return "";
		}
		int charNum = getCharNum(specifications);
		String designNum =StringUtils.hasLength(chOrderBom.getDesignNum()) ? chOrderBom.getDesignNum() : "0";//订购数量
		if (charNum == 1){// Φ160X15  圆料
			weight=roundMaterialCalculationWeight(specifications, materialCode,designNum);
		}else if (charNum == 2){//方料
			weight=calculatedWeightOfSquareMaterial(specifications,materialCode,designNum);
		}
		return weight;
	}

	 /**
	  * 圆料计算重量
	  * @param specifications 规格
	  * @param materialCode  物料编码
	  * @return
	  */
	public String roundMaterialCalculationWeight(String specifications,String materialCode,String designNum){
		String[] split = specifications.split(CommonMst.Data_Division_Constant.Division_Constant);
		String diameter = split[0]; //直径
		diameter = diameter.substring(1);//直径  去掉Φ
		String longNum = split[1]; //长度
		//获取密度
		String density = getDensity(materialCode);
		String radius = String.valueOf(BigDecimalUtil.divide(Double.parseDouble(diameter), 2));//半径
		//公式计算
		Double multiply = BigDecimalUtil.multiply(CommonMst.ORDER_BOM.π, radius, radius, longNum, density,designNum);
		double divide = BigDecimalUtil.divide(multiply, CommonMst.ORDER_BOM.NUM, CommonMst.ORDER_BOM.KEEP_DECIMALS);
		return String.valueOf(divide);
	}


	 /**
	  * 方料计算重量
	  * @param specifications 规格
	  * @return
	  */
	public String calculatedWeightOfSquareMaterial(String specifications,String materialCode,String designNum){
		String[] split = specifications.split(CommonMst.Data_Division_Constant.Division_Constant);
		String longNum = split[0];//长
		String withNum = split[1];//宽
		String HighNum = split[2];//高
		String density = getDensity(materialCode);//密度
		Double longAndwithAndHigh = BigDecimalUtil.multiply(longNum, withNum,HighNum,density,designNum);
		double divide = BigDecimalUtil.divide(longAndwithAndHigh, CommonMst.ORDER_BOM.NUM, CommonMst.ORDER_BOM.KEEP_DECIMALS);
		return String.valueOf(divide);
	}

	 /**
	  * 获取密度
	  * @param materialCode 物料编码
	  * @return
	  */
	public String getDensity(String materialCode){
		LambdaQueryWrapper<ChMaterialCodeRawMaterial> chMaterialCodeRawMaterialLambdaQueryWrapper = new QueryWrapper<ChMaterialCodeRawMaterial>().lambda()
				.eq(ChMaterialCodeRawMaterial::getItemCode, materialCode);
		List<ChMaterialCodeRawMaterial> chMaterialCodeRawMaterialList = iChMaterialCodeRawMaterialService.list(chMaterialCodeRawMaterialLambdaQueryWrapper);
		if (CollectionUtils.isEmpty(chMaterialCodeRawMaterialList)){
			throw new RuntimeException(materialCode+"该料件编码未维护密度!");
		}
		String density = chMaterialCodeRawMaterialList.get(0).getDensity();//密度
		return density;
	}

	 /**
	  * 获取指定字符的个数
	  * @param str
	  * @return
	  */
	public int getCharNum(String str){
		String[] split = str.split(CommonMst.Data_Division_Constant.Division_Constant);
		int DotCount = split.length- 1;
		return  DotCount;
	}


	 /**
	  *  编辑（给鼎捷提供的接口）
	  * @param chOrderBom
	  * @return
	  */
	 @AutoLog(value = "订购BOM-（给鼎捷提供的接口）")
	 @ApiOperation(value="订购BOM-（给鼎捷提供的接口）", notes="订购BOM-（给鼎捷提供的接口）")
	 //@RequiresPermissions("org.jeecg.modules.demo:ch_order_bom:edit")
	 @RequestMapping(value = "/editForDJ", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<ChOrderBom> editForDJ(@RequestBody ChOrderBom chOrderBom) {
		 log.info("传过来的参数chOrderBom:{}",chOrderBom);
		 String withoutAllowanceDimension1 = chOrderBom.getWithoutAllowanceDimension();//未加余量尺寸
		 //将未加余量尺寸 包含的x替换为X
		 if (StringUtils.hasLength(withoutAllowanceDimension1)){
			 withoutAllowanceDimension1=withoutAllowanceDimension1.replace(CommonMst.Data_Division_Constant.Little_Division_Constant, CommonMst.Data_Division_Constant.Division_Constant);
			 chOrderBom.setWithoutAllowanceDimension(withoutAllowanceDimension1);
		 }
		 //tip1:原材料以及为空的逻辑 赋值料件编码和料件名称
		 chOrderBom.setMaterialCode("");//料件编码
		 chOrderBom.setMaterialName("");//料件名称

		 chOrderBom.setSpecifications("");//规格
		 chOrderBom.setSpecificationsDescription("");//规格说明
		 chOrderBom.setSoftAndHardMaterials("");//软硬料
		 chOrderBom.setFineWool("");//精毛料

		 String fineWool = "";//精毛料
		 String softAndHardMaterials = "";//软硬料
		 String bulkPartsType = chOrderBom.getBulkPartsType();//散件类型
		 //初始化更新
		 if (!StringUtils.hasLength(chOrderBom.getErpCode())){
			// chOrderBomService.saveOrUpdate(chOrderBom);
			 return Result.OK(chOrderBom);
		 }
		 if (!StringUtils.hasLength(bulkPartsType)){//为空时赋值 空
			 bulkPartsType = CommonMst.ORDER_BOM.EMPTY;
		 }
		 if (!StringUtils.hasLength(chOrderBom.getRawMaterialsAndAccessories()) || CommonMst.ORDER_BOM.RAW_MATERIAL.equals(chOrderBom.getRawMaterialsAndAccessories())){//  原材料
			 //根据erp代码的代码转大写查找原材料对照表中的料件编码
			 LambdaQueryWrapper<ChRawMaterialCodeComparison> ChRawMaterialCodeComparisonWrapper = new QueryWrapper<ChRawMaterialCodeComparison>().lambda();
			 if (StringUtils.hasLength(chOrderBom.getErpCode())){
				 ChRawMaterialCodeComparisonWrapper.eq(StringUtils.hasLength(chOrderBom.getErpCode()),ChRawMaterialCodeComparison::getErpCode,chOrderBom.getErpCode().toUpperCase());
			 }
			 List<ChRawMaterialCodeComparison> chRawMaterialCodeComparisonList = iChRawMaterialCodeComparisonService.list(ChRawMaterialCodeComparisonWrapper);
			 if (chRawMaterialCodeComparisonList.isEmpty() || chRawMaterialCodeComparisonList.size() == 0){
				 log.error("ERP代码有误,请检查！根据erp代码在原材料对照表中未找到对应的物料编码原材料表id!");
				 return Result.custom_Error("ERP代码有误,请检查！根据erp代码在原材料对照表中未找到对应的物料编码原材料表id!");
			 }
			 String chMaterialCodeRawMaterialId = chRawMaterialCodeComparisonList.get(0).getChMaterialCodeRawMaterialId();//物料编码原材料类表id
			 //根据物料编码原材料表id查找料件编码
			 LambdaQueryWrapper<ChMaterialCodeRawMaterial> chMaterialCodeRawMaterialLambdaQueryWrapper = new QueryWrapper<ChMaterialCodeRawMaterial>().lambda();
			 chMaterialCodeRawMaterialLambdaQueryWrapper.eq(ChMaterialCodeRawMaterial::getId,chMaterialCodeRawMaterialId);
			 List<ChMaterialCodeRawMaterial> chMaterialCodeRawMaterialList = iChMaterialCodeRawMaterialService.list(chMaterialCodeRawMaterialLambdaQueryWrapper);
			 if (chMaterialCodeRawMaterialList.isEmpty() || chMaterialCodeRawMaterialList.size() == 0){
				 log.error("ERP代码有误,请检查！根据物料编码原材料类表id查找数据为空!");
				 return Result.custom_Error("ERP代码有误,请检查！根据物料编码原材料类表id查找数据为空!");
			 }
			 chOrderBom.setMaterialCode(OrderBomUtils.setStringIfNotNull(chMaterialCodeRawMaterialList.get(0).getItemCode()));//料件编码
			 chOrderBom.setMaterialName(OrderBomUtils.setStringIfNotNull(chMaterialCodeRawMaterialList.get(0).getItemName()));//料件名称
			 chOrderBom.setT100Units(OrderBomUtils.setStringIfNotNull(chMaterialCodeRawMaterialList.get(0).getUnit()));//设置单位
			 softAndHardMaterials=chMaterialCodeRawMaterialList.get(0).getSoftAndHardMaterials();
			 fineWool=chMaterialCodeRawMaterialList.get(0).getFineWool();
			 chOrderBom.setSoftAndHardMaterials(OrderBomUtils.setStringIfNotNull(softAndHardMaterials));//软硬料
			 chOrderBom.setFineWool(OrderBomUtils.setStringIfNotNull(fineWool));//精毛料

			 //2.原材料情况下 订料和不订料的逻辑  赋值规格和规格说明
			 String mixMaterialsAndNotOrder = chOrderBom.getMixMaterialsAndNotOrder();//拼料和不订料
			 String withoutAllowanceDimension = chOrderBom.getWithoutAllowanceDimension();//未加余量的尺寸
			 //	withoutAllowanceDimension = OrderBomUtils.eliminateRedundantZeros(withoutAllowanceDimension);//去除多余的零
			 if (StringUtils.hasLength(mixMaterialsAndNotOrder) && CommonMst.ORDER_BOM.SPLICING.equals(mixMaterialsAndNotOrder)){//拼料的情况下
				 if (StringUtils.hasLength(withoutAllowanceDimension)){
					 chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
					 chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
				 }
			 }else if (StringUtils.hasLength(mixMaterialsAndNotOrder) && CommonMst.ORDER_BOM.NO_ORDER.equals(mixMaterialsAndNotOrder)){//不订料的情况下
				 if (StringUtils.hasLength(withoutAllowanceDimension)){
					 chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
					 chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
				 }
			 }else if (!StringUtils.hasLength(mixMaterialsAndNotOrder)){//为空的情况下
				 //3.原材料以及为空的逻辑 是圆料还是方料的情况 赋值规格和规格说明  未加余量尺寸首字母是数字为圆料，其他为方料
				 //判断首字母是否为数字
				 Boolean aBoolean = OrderBomUtils.FirstCharIsNumber(withoutAllowanceDimension);
				 if (!aBoolean){//圆料
					 chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
					 chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
				 }else {//方料
					 //获取精毛料
					 if (StringUtils.hasLength(fineWool) && CommonMst.ORDER_BOM.CONCENTRATE.equals(fineWool)){//精料
						 //精料的情况下判断软硬料 加余量 以及 公差
						 if (StringUtils.hasLength(softAndHardMaterials) && CommonMst.ORDER_BOM.HARD_MATERIAL.equals(softAndHardMaterials)){//硬料
							 addMarginAccordingToSize(CommonMst.ORDER_BOM.HARD_MATERIAL, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType, withoutAllowanceDimension,chOrderBom);
							 sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.HARD_MATERIAL, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType,chOrderBom);

						 }else if (StringUtils.hasLength(softAndHardMaterials) && CommonMst.ORDER_BOM.HARD_MATERIAL2.equals(softAndHardMaterials)){//硬料2
							 addMarginAccordingToSize(CommonMst.ORDER_BOM.HARD_MATERIAL2, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType, withoutAllowanceDimension,chOrderBom);
							 sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.HARD_MATERIAL2, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType,chOrderBom);

						 }else if (StringUtils.hasLength(softAndHardMaterials) && CommonMst.ORDER_BOM.SOFT_MATERIAL.equals(softAndHardMaterials)){//软料
							 addMarginAccordingToSize(CommonMst.ORDER_BOM.SOFT_MATERIAL, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType, withoutAllowanceDimension,chOrderBom);
							 sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.SOFT_MATERIAL, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType,chOrderBom);

						 }else if (StringUtils.hasLength(softAndHardMaterials) && CommonMst.ORDER_BOM.SOFT_MATERIAL2.equals(softAndHardMaterials)){//软料2
							 addMarginAccordingToSize(CommonMst.ORDER_BOM.SOFT_MATERIAL2, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType, withoutAllowanceDimension,chOrderBom);
							 sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.SOFT_MATERIAL2, CommonMst.ORDER_BOM.PARTS_TYP, bulkPartsType,chOrderBom);

						 }else {
							 log.info("传过来的参数软硬料softAndHardMaterials:{}暂不做处理!",softAndHardMaterials);
						 }

					 }else if (StringUtils.hasLength(fineWool) && CommonMst.ORDER_BOM.WOOL.equals(fineWool)){//毛料
						 chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
						 chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
					 }else if (StringUtils.hasLength(fineWool) && CommonMst.ORDER_BOM.WOOL2.equals(fineWool)){//毛料2
						 //规格和规格说明  赋值时  加二有小数点就进一
						 withoutAllowanceDimension = OrderBomUtils.DataRoundedUp(withoutAllowanceDimension);
						 chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
						 chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
						 sequencingAndsplicingTolerances(CommonMst.ORDER_BOM.NOTHING, CommonMst.ORDER_BOM.PARTS_TYP, CommonMst.ORDER_BOM.EMPTY,chOrderBom);

					 }else if (StringUtils.hasLength(fineWool) && CommonMst.ORDER_BOM.NOTHING.equals(fineWool)){//无
						 chOrderBom.setSpecifications(withoutAllowanceDimension);//设置规格
						 chOrderBom.setSpecificationsDescription(withoutAllowanceDimension);//设置规格说明
					 }else {
						 log.info("传过来的精毛料fineWool:{}暂不做处理!",fineWool);
					 }
				 }
			 }else {
				 log.error("传过来的拼料和不订料mixMaterialsAndNotOrder:{}暂不做处理",mixMaterialsAndNotOrder);
				 return Result.custom_Error("传过来的拼料和不订料mixMaterialsAndNotOrder:{}暂不做处理"+mixMaterialsAndNotOrder);
			 }


			 //tip2:配件逻辑
		 }else if (StringUtils.hasLength(chOrderBom.getRawMaterialsAndAccessories()) && CommonMst.ORDER_BOM.PARTS.equals(chOrderBom.getRawMaterialsAndAccessories())){//配件
			 //根据erp代码的代码转大写查找配件类对照表中的料件编码
			 LambdaQueryWrapper<ChPartsCodeComparison> chPartsCodeComparisonLambdaQueryWrapper = new QueryWrapper<ChPartsCodeComparison>().lambda();
			 chPartsCodeComparisonLambdaQueryWrapper.eq(ChPartsCodeComparison::getErpCode,chOrderBom.getErpCode().toUpperCase());
			 List<ChPartsCodeComparison> chPartsCodeComparisonList  = iChPartsCodeComparisonService.list(chPartsCodeComparisonLambdaQueryWrapper);
			 if (chPartsCodeComparisonList.isEmpty() || chPartsCodeComparisonList.size() == 0){
				 log.error("ERP代码有误,请检查！根据erp代码在配件代码对照表中未找到对应的物料编码配件类表id!");
				 return Result.custom_Error("ERP代码有误,请检查！根据erp代码在配件代码对照表中未找到对应的物料编码配件类表id!");
			 }
			 String chMaterialCodeRawMaterialId = chPartsCodeComparisonList.get(0).getChMaterialCodeAccessoriesId();//物料编码配件类表id
			 //根据物料编码配件类表id查找料件编码暂存
			 LambdaQueryWrapper<ChMaterialCodeAccessories> chMaterialCodeAccessoriesLambdaQueryWrapper = new QueryWrapper<ChMaterialCodeAccessories>().lambda();
			 chMaterialCodeAccessoriesLambdaQueryWrapper.eq(ChMaterialCodeAccessories::getId,chMaterialCodeRawMaterialId);
			 List<ChMaterialCodeAccessories> chMaterialCodeAccessoriesList = iChMaterialCodeAccessoriesService.list(chMaterialCodeAccessoriesLambdaQueryWrapper);
			 if (chMaterialCodeAccessoriesList.isEmpty() || chMaterialCodeAccessoriesList.size() == 0){
				 log.error("ERP代码有误,请检查！根据物料编码配件类表id查找数据为空!");
				 return Result.custom_Error("ERP代码有误,请检查！根据物料编码配件类表id查找数据为空!");
			 }
			 String itemCode = chMaterialCodeAccessoriesList.get(0).getItemCode();//暂存
			 String itemName = chMaterialCodeAccessoriesList.get(0).getItemName();//暂存
			 String unit = chMaterialCodeAccessoriesList.get(0).getUnit();//暂存

			 //根据订购BPM版面中的ERP代码+未加余量的尺寸精确匹配配件代码对照表中的ERP代码.
			 String erpCode = chOrderBom.getErpCode();
			 String withoutAllowanceDimension = chOrderBom.getWithoutAllowanceDimension();
			 if (StringUtils.hasLength(withoutAllowanceDimension)){
				 erpCode = erpCode+withoutAllowanceDimension;
			 }
			 //根据erp代码的代码转大写查找配件类对照表中的料件编码
			 LambdaQueryWrapper<ChPartsCodeComparison> chPartsCodeComparisonLambdaQueryWrapperTwo = new QueryWrapper<ChPartsCodeComparison>().lambda();
			 chPartsCodeComparisonLambdaQueryWrapperTwo.eq(ChPartsCodeComparison::getErpCode,erpCode.toUpperCase());
			 List<ChPartsCodeComparison> chPartsCodeComparisons  = iChPartsCodeComparisonService.list(chPartsCodeComparisonLambdaQueryWrapperTwo);
			 if (chPartsCodeComparisons.isEmpty() || chPartsCodeComparisons.size() == 0){ //查询为空
				 //将初始的料件编码赋值到订购BOM中料件编码栏位中
				 chOrderBom.setMaterialCode(itemCode);
				 chOrderBom.setMaterialName(itemName);
				 chOrderBom.setT100Units(unit);
			 }else {
				 String chMaterialCodeAccessoriesId = chPartsCodeComparisons.get(0).getChMaterialCodeAccessoriesId();//物料编码配件类表id
				 LambdaQueryWrapper<ChMaterialCodeAccessories> chMaterialCodeAccessoriesLambdaQueryWrapperTwo = new QueryWrapper<ChMaterialCodeAccessories>().lambda();
				 chMaterialCodeAccessoriesLambdaQueryWrapperTwo.eq(ChMaterialCodeAccessories::getId,chMaterialCodeAccessoriesId);
				 List<ChMaterialCodeAccessories> chMaterialCodeAccessories = iChMaterialCodeAccessoriesService.list(chMaterialCodeAccessoriesLambdaQueryWrapperTwo);
				 if (chMaterialCodeAccessories.isEmpty() || chMaterialCodeAccessories.size() == 0){
					 log.error("ERP代码有误,请检查！根据物料编码配件类表id查找数据为空!");
					 return Result.custom_Error("ERP代码有误,请检查！根据物料编码配件类表id查找数据为空!");
				 }
				 itemCode = chMaterialCodeAccessories.get(0).getItemCode();//暂存
				 chOrderBom.setMaterialCode(OrderBomUtils.setStringIfNotNull(itemCode));
				 chOrderBom.setMaterialName(OrderBomUtils.setStringIfNotNull(chMaterialCodeAccessories.get(0).getItemName()));
				 chOrderBom.setT100Units(OrderBomUtils.setStringIfNotNull(chMaterialCodeAccessories.get(0).getUnit()));
			 }
			 chOrderBom.setSpecifications(OrderBomUtils.setStringIfNotNull(withoutAllowanceDimension));//配件类的直接赋值未加余量尺寸
			 chOrderBom.setSpecificationsDescription(OrderBomUtils.setStringIfNotNull(withoutAllowanceDimension));//配件类的直接赋值未加余量尺寸
		 }else {
			 //传来的原材料及配件是
			 String rawMaterialsAndAccessories = chOrderBom.getRawMaterialsAndAccessories();
			 return Result.custom_Error("传来的原材料及配件rawMaterialsAndAccessories:{}暂不做处理!"+rawMaterialsAndAccessories);
		 }
		 String weight = getWeight(chOrderBom);
		 chOrderBom.setWeight(weight);
		 //设置是否是库存标准件
		 String isStandardPart = getIsStandardPart(chOrderBom);
		 chOrderBom.setIsStandardPart(isStandardPart);
		 log.info("匹配到的料件编码itemCode:{},itemName料件名称:{}",chOrderBom.getMaterialCode(),chOrderBom.getMaterialName());
		 //chOrderBomService.updateById(chOrderBom);
//		 chOrderBomService.saveOrUpdate(chOrderBom);
		 return Result.OK(chOrderBom);
	 }


	 /**
	  * 设置规格和规格说明
	  * @param major_categories 大类
	  * @param middle_class  中类
	  * @param little_class  小类
	  * @param withoutAllowanceDimension 规格
	  * @param chOrderBom 返回的订购BOM
	  * @return
	  */
	public void addMarginAccordingToSize(String major_categories,String middle_class,String little_class,String withoutAllowanceDimension,ChOrderBom chOrderBom){
		if (!StringUtils.hasLength(withoutAllowanceDimension) || !withoutAllowanceDimension.contains(CommonMst.Data_Division_Constant.Division_Constant)){
			return ;
		}
		log.info("根据传来的大类major_categories:{},中类middle_class:{},小类little_class:{}余量withoutAllowanceDimension:{},",major_categories,middle_class,little_class,withoutAllowanceDimension);
		LambdaQueryWrapper<ChAllowance> chAllowanceLambdaQueryWrapper = new QueryWrapper<ChAllowance>().lambda();
		chAllowanceLambdaQueryWrapper.eq(StringUtils.hasLength(major_categories),ChAllowance::getMajorCategories,major_categories);
		chAllowanceLambdaQueryWrapper.eq(StringUtils.hasLength(middle_class),ChAllowance::getMiddleClass,middle_class);
		chAllowanceLambdaQueryWrapper.eq(StringUtils.hasLength(little_class),ChAllowance::getLittleClass,little_class);
		List<ChAllowance> list = iChAllowanceService.list(chAllowanceLambdaQueryWrapper);
		if (list.isEmpty() || list.size() == 0){
			log.error("根据传来的大类major_categories:{},中类middle_class:{},小类little_class:{}余量withoutAllowanceDimension:{}未匹配到值,",major_categories,middle_class,little_class,withoutAllowanceDimension);
		    return ;
		}

		String[] split = withoutAllowanceDimension.split(CommonMst.Data_Division_Constant.Division_Constant);
		Double longStr = Double.parseDouble(split[0]);
		Double wideStr = Double.parseDouble(split[1]);
		Double highStr = Double.parseDouble(split[2]);

		String longEnd="";//长加完余量以后的值
		String wideEnd="";//宽加完余量以后的值
		String highEnd="";//高加完余量以后的值

		//分别进行加余量
		for (ChAllowance chAllowance : list) {
			Integer longGreaterThan = chAllowance.getLongGreaterThan();//长大于
			Integer longLessThanEqual = chAllowance.getLongLessThanEqual();//长小于等于
			String  longAllowance = chAllowance.getLongAllowance();//长余量
			Integer wideGreaterThan = chAllowance.getWideGreaterThan();//宽大于
			Integer wideLessThanEqual = chAllowance.getWideLessThanEqual();//宽小于等于
			String  wideAllowance = chAllowance.getWideAllowance();//宽余量
			Integer highGreaterThan = chAllowance.getHighGreaterThan();//宽大于
			Integer highLessThanEqual = chAllowance.getHighLessThanEqual();//宽小于等于
			String  highAllowance = chAllowance.getHighAllowance();//宽余量

			if (longStr > longGreaterThan && longStr <= longLessThanEqual){
				String longTemp =String.valueOf(BigDecimalUtil.add(String.valueOf(longStr), longAllowance));
				BigDecimal bigDecimal = new BigDecimal(longTemp);
				longEnd = bigDecimal.setScale(1, BigDecimal.ROUND_UP).toString();//有小数点 进一
			}
			if (wideStr > wideGreaterThan && wideStr <= wideLessThanEqual){
				String wideTemp = String.valueOf(BigDecimalUtil.add(String.valueOf(wideStr), String.valueOf(Double.parseDouble(wideAllowance))));
				BigDecimal bigDecimal = new BigDecimal(wideTemp);
				wideEnd = bigDecimal.setScale(1, BigDecimal.ROUND_UP).toString();//有小数点 进一
			}
			if (highStr > highGreaterThan && highStr <= highLessThanEqual){
				String highTemp =String.valueOf(BigDecimalUtil.add(String.valueOf(highStr), String.valueOf(Double.parseDouble(highAllowance))));
				BigDecimal bigDecimal = new BigDecimal(highTemp);
				highEnd = bigDecimal.setScale(1, BigDecimal.ROUND_UP).toString();//有小数点 进一
			}
		}
		//组装返回的数据
		ArrayList<String> lists = new ArrayList<>();//存放加余量之后的数据
		lists.add(longEnd);
		lists.add(wideEnd);
		lists.add(highEnd);
		String join = org.apache.commons.lang3.StringUtils.join(lists.toArray(), CommonMst.Data_Division_Constant.Division_Constant);
		chOrderBom.setSpecifications(join);
		chOrderBom.setSpecificationsDescription(join);
		return ;
	}



	 /**
	  * 根据需要进行规格排序 拼接公差 设置规格说明
	  * @param major_categories 大类
	  * @param middle_class  中类
	  * @param little_class  小类
	  * @param chOrderBom 返回的订购BOM
	  * @return
	  */
	 public void sequencingAndsplicingTolerances(String major_categories,String middle_class,String little_class,ChOrderBom chOrderBom){
		 String withoutAllowanceDimension = chOrderBom.getSpecifications();
		 if (!StringUtils.hasLength(withoutAllowanceDimension)){
			 return ;
		 }
		 if (!withoutAllowanceDimension.contains(CommonMst.Data_Division_Constant.Division_Constant)){
			 return;
		 }
		 log.info("根据传来的大类major_categories:{},中类middle_class:{},小类little_class:{}余量withoutAllowanceDimension:{},",major_categories,middle_class,little_class,withoutAllowanceDimension);
		 LambdaQueryWrapper<ChAllowance> chAllowanceLambdaQueryWrapper = new QueryWrapper<ChAllowance>().lambda();
		 chAllowanceLambdaQueryWrapper.eq(StringUtils.hasLength(major_categories),ChAllowance::getMajorCategories,major_categories);
		 chAllowanceLambdaQueryWrapper.eq(StringUtils.hasLength(middle_class),ChAllowance::getMiddleClass,middle_class);
		 chAllowanceLambdaQueryWrapper.eq(StringUtils.hasLength(little_class),ChAllowance::getLittleClass,little_class);
		 List<ChAllowance> list = iChAllowanceService.list(chAllowanceLambdaQueryWrapper);
		 if (list.isEmpty() || list.size() == 0){
			 log.error("根据传来的大类major_categories:{},中类middle_class:{},小类little_class:{}余量withoutAllowanceDimension:{}未匹配到值,",major_categories,middle_class,little_class,withoutAllowanceDimension);
			 return ;
		 }

		 String[] split = withoutAllowanceDimension.split(CommonMst.Data_Division_Constant.Division_Constant);
		 Double longStr = Double.parseDouble(split[0]);
		 Double wideStr = Double.parseDouble(split[1]);
		 Double highStr = Double.parseDouble(split[2]);
		 double[] doubles = new double[]{longStr,wideStr,highStr};//初始化数组

		 //因为避免再多建立一张表，数据库是多条,公差是按类型匹配理论上都是重复的 那么此时只取其中的一条
		 String isReadBasicTable = list.get(0).getIsReadBasicTable();//是否读基础表
		 String sortOrNot = list.get(0).getSortOrNot();//是否需要排序
		 String lengthTolerance = list.get(0).getLengthTolerance();//长度公差
		 String wideTolerance = list.get(0).getWideTolerance();//宽度公差
		 String highTolerance = list.get(0).getHighTolerance();//高度公差

		 if (StringUtils.hasLength(isReadBasicTable) && CommonMst.ORDER_BOM.YES.equals(isReadBasicTable)){
			 //根据料件编码 读取前两个数公差以及第三个数公差
			 String materialCode = chOrderBom.getMaterialCode();
			 LambdaQueryWrapper<ChMaterialCodeRawMaterial> chMaterialCodeRawMaterialLambdaQueryWrapper = new QueryWrapper<ChMaterialCodeRawMaterial>().lambda();
			 chMaterialCodeRawMaterialLambdaQueryWrapper.eq(ChMaterialCodeRawMaterial::getItemCode,materialCode);
			 List<ChMaterialCodeRawMaterial> materialCodeRawMaterials = iChMaterialCodeRawMaterialService.list(chMaterialCodeRawMaterialLambdaQueryWrapper);
			 if (materialCodeRawMaterials.isEmpty() || materialCodeRawMaterials.size() == 0){
				 log.info("根据料件编码materialCode:{}未从基础表中查询到数据",materialCode);
			 }else {
				 String firstTwoNumTolerance = materialCodeRawMaterials.get(0).getFirstTwoNumTolerance();//前两个数公差
				 String thirdNumTolerance = materialCodeRawMaterials.get(0).getThirdNumTolerance();//第三个数公差
				 lengthTolerance=firstTwoNumTolerance;
				 wideTolerance=firstTwoNumTolerance;
				 highTolerance=thirdNumTolerance;
			 }
		 }
		 if (StringUtils.hasLength(sortOrNot) && CommonMst.ORDER_BOM.YES.equals(sortOrNot)){
			 //根据长宽高进行依次排序  进行数组的降序
			 OrderBomUtils.orderNum(doubles);
		 }
		 //进行数组的长宽高加公差
		 //加完公差以后的值
		 if (!StringUtils.hasLength(lengthTolerance)){
			 lengthTolerance="";
		 }
		 if (!StringUtils.hasLength(wideTolerance)){
			 wideTolerance="";
		 }
		 if (!StringUtils.hasLength(highTolerance)){
			 highTolerance="";
		 }
		 String longToLeranceBefore  = String.valueOf(doubles[0]); //长加完公差以后的值
		 String wideToLeranceBefore  = String.valueOf(doubles[1]); //宽加完公差以后的值
		 String highToLeranceBefore  = String.valueOf(doubles[2]); //高加完公差以后的值
		 //去零操作
		 ArrayList<String> arrayListTemp = new ArrayList<>();//存放加公差之前的数据
		 arrayListTemp.add(longToLeranceBefore);
		 arrayListTemp.add(wideToLeranceBefore);
		 arrayListTemp.add(highToLeranceBefore);
		 String specifications = org.apache.commons.lang3.StringUtils.join(arrayListTemp.toArray(), CommonMst.Data_Division_Constant.Division_Constant);
		 specifications = OrderBomUtils.eliminateRedundantZeros(specifications);//去除多余的零
		 chOrderBom.setSpecifications(specifications);//重新赋值规格

		 //将去零后的数据进行加公差
		 String[] split1 = specifications.split(CommonMst.Data_Division_Constant.Division_Constant);
		 String longToLerance  = split1[0]+lengthTolerance; //长加完公差以后的值
		 String wideToLerance  = split1[1]+wideTolerance; //宽加完公差以后的值
		 String highToLerance  = split1[2]+highTolerance; //高加完公差以后的值

		 ArrayList<String> arrayList = new ArrayList<>();//存放加公差之后的数据
		 arrayList.add(longToLerance);
		 arrayList.add(wideToLerance);
		 arrayList.add(highToLerance);
		 String join = org.apache.commons.lang3.StringUtils.join(arrayList.toArray(), CommonMst.Data_Division_Constant.Division_Constant);
		 chOrderBom.setSpecificationsDescription(join);//重新赋值规格说明
		 return ;
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "订购BOM-通过id删除")
	@ApiOperation(value="订购BOM-通过id删除", notes="订购BOM-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:ch_order_bom:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		chOrderBomService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "订购BOM-批量删除")
	@ApiOperation(value="订购BOM-批量删除", notes="订购BOM-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:ch_order_bom:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.chOrderBomService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "订购BOM-通过id查询")
	@ApiOperation(value="订购BOM-通过id查询", notes="订购BOM-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ChOrderBom> queryById(@RequestParam(name="id",required=true) String id) {
		ChOrderBom chOrderBom = chOrderBomService.getById(id);
		if(chOrderBom==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(chOrderBom);
	}

//    /**
//    * 导出excel
//    *
//    * @param request
//    * @param chOrderBom
//    */
//    //@RequiresPermissions("org.jeecg.modules.demo:ch_order_bom:exportXls")
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(HttpServletRequest request, ChOrderBom chOrderBom) {
//        return super.exportXls(request, chOrderBom, ChOrderBom.class, "订购BOM");
//    }


	 @RequestMapping("exportXls")
	 public void exportExcel(HttpServletRequest request,HttpServletResponse response, ChOrderBom chOrderBom) throws UnsupportedEncodingException {
		 // 设置响应类型
		 response.setContentType("application/vnd.ms-excel");
		 // 设置字符编码
		 response.setCharacterEncoding("utf-8");
		 // 设置响应头信息
		 response.setHeader("Content-disposition",
				 "attachment;filename*=utf-8''" + URLEncoder.encode("转T100请购单-模板", "UTF-8") + ".xlsx");
		 //构建要导出的集合
		 ArrayList<OrderBomExcel> orderBomExcelArrayList = getExportList(request);

		 // 写入文件
		 ExcelWriter writer = ExcelUtil.getWriter();
		 // 设置标题一样式
		 CellStyle cellStyle1 = writer.createCellStyle();
		 cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);
		 cellStyle1.setAlignment(HorizontalAlignment.CENTER);
		 cellStyle1.setBorderLeft(writer.getCellStyle().getBorderLeft());
		 cellStyle1.setBorderRight(writer.getCellStyle().getBorderRight());
		 cellStyle1.setBorderBottom(writer.getCellStyle().getBorderBottom());
		 Font font = writer.createFont();
		 font.setBold(true);
		 font.setFontHeightInPoints((short) 12);
		 font.setFontName("微软雅黑");
		 cellStyle1.setFont(font);

		 // 设置“标题” 单元格样式
		 CellStyle cellStyle = writer.createCellStyle();
		 cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GOLD.getIndex());
		 cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		 //设置垂直居中和水平居中
		 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		 cellStyle.setAlignment(HorizontalAlignment.LEFT);
		 //设置边框
		 cellStyle.setBorderRight(writer.getCellStyle().getBorderRight());
		 cellStyle.setBorderBottom(writer.getCellStyle().getBorderBottom());

		 // 标题一
		//	writer.merge(0,0,0,11, "BOM报价单", cellStyle1);

		 // 列合并
		 writer.merge(3,4,9,9, "材料订购录入带公差的和单位是“KG”的规格", cellStyle1);
		 writer.merge(2,3,8,8, "001:超BOM用量请购\n" +
				 "002:正常请购\n" +
				 "003:客户设变\n" +
				 "004:报废重订\n" +
				 "005:增加备用件\n" +
				 "006:设计方案变更", cellStyle);

		 // 跳过前面四行（为了设置标题样式）原始的设置标题方法，不可以，例：merge(3, "标题名", false);
		// writer.passRows(4);

//		 // 设置高度（行row）
//		 writer.setRowHeight(0, 50);
//		 writer.setRowHeight(1, 30);

		 // 设置导出信息的表头
//		 writer.addHeaderAlias("sno", "学号");


		 // 设置列宽（Colum）
		 for (int i = 0; i <= 13; i++) {
			  if (i==2 || i==6){
				  writer.setColumnWidth(i, 20);
			  }else if (i==9){
				  writer.setColumnWidth(i, 40);
			  }else {
				  writer.setColumnWidth(i, 15);
			  }
		 }

		 // 设置导出表头样式，但不包括合并单元格
		 CellStyle headCellStyle = writer.getHeadCellStyle();

		 // headCellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIME.getIndex());
		 headCellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.YELLOW.getIndex());
		 headCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

		 // 写入
		 writer.write(orderBomExcelArrayList, true);

		 // 主要针对自定义表头设置 行高（必须要写入完成后才可以设置）
		 for (int i = 1; i < orderBomExcelArrayList.size(); i++) {
			 writer.setRowHeight(i,20);
		 }

		 try {
			 writer.flush(response.getOutputStream(), true);
		 } catch (IOException e) {
			 e.printStackTrace();
		 } finally {
			 writer.close();
		 }
	 }

	 /**
	  * 构建要导出的集合
	  * @param request
	  * @return
	  */
	 public ArrayList<OrderBomExcel> getExportList(HttpServletRequest request){
		 //构建初始数据
		 ArrayList<OrderBomExcel> orderBomExcelArrayList = new ArrayList<OrderBomExcel>(){
			 {
				 add(new OrderBomExcel("项次", "料件编号", "库存管理特征", "单位", "需求数量",
						 "计价单位", "计价数量","需求日期","理由码","备注","紧急度",
						 "部位编号","请购件数","模具编号"));
				 add(new OrderBomExcel("", "", "录入“模具材料规格”", "", "",
						 "", "","","001:超BOM用量请购\n" +
						 "002:正常请购\n" +
						 "003:客户设变\n" +
						 "004:报废重订\n" +
						 "005:增加备用件\n" +
						 "006:设计方案变更\n","","1：一般",
						 "","",""));
				 add(new OrderBomExcel("", "", "乘号大写“X”", "", "",
						 "", "","","001:超BOM用量请购\n" +
						 "002:正常请购\n" +
						 "003:客户设变\n" +
						 "004:报废重订\n" +
						 "005:增加备用件\n" +
						 "006:设计方案变更\n","材料订购录入带公差的和单位是“KG”的规格","2：紧急",
						 "","",""));
				 add(new OrderBomExcel("", "物料编码", "直径“Φ”（Alt+42677）", "", "",
						 "", "","YYYY/MM/DD","001~006","材料订购录入带公差的和单位是“KG”的规格","3：特急",
						 "零件名","整数","营业部建立"));
			 }
		 };

		 //设置自定义导出的数据
		 List<ChOrderBom> exportList = new ArrayList<>(); //默认导出空数据
		 QueryWrapper<ChOrderBom> chOrderBomQueryWrapper = new QueryWrapper<>();
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 chOrderBomQueryWrapper.in("id",selectionList);
			 // Step.2 获取导出数据
			 exportList = service.list(chOrderBomQueryWrapper);
		 }
		 ArrayList<OrderBomExcel> orderBomExcels = new ArrayList<>(); //封装构建需要导出的数据
		 if (!exportList.isEmpty() && exportList.size() > 0){ //不为空
			 for (ChOrderBom orderBom : exportList) {

				 OrderBomExcel orderBomExcel = new OrderBomExcel();//实体映射
				 orderBomExcel.setPmdbseq(OrderBomUtils.setStringIfNotNull(orderBom.getDesignSerialNo()));//项次
				 orderBomExcel.setPmdb004(OrderBomUtils.setStringIfNotNull(orderBom.getMaterialCode()));//物料编码
				 orderBomExcel.setPmdb054(OrderBomUtils.setStringIfNotNull(orderBom.getSpecifications()));//规格
				 orderBomExcel.setPmdb007(OrderBomUtils.setStringIfNotNull(orderBom.getT100Units()));//T100单位
				 orderBomExcel.setPmdb006(OrderBomUtils.setStringIfNotNull(orderBom.getDesignNum()));//数量
				 orderBomExcel.setPmdb011(OrderBomUtils.setStringIfNotNull(orderBom.getT100Units()));//T100单位
				 orderBomExcel.setPmdb010(OrderBomUtils.setStringIfNotNull(orderBom.getDesignNum()));//数量
				 orderBomExcel.setPmdb030(OrderBomUtils.setStringIfNotNull(orderBom.getT100DemandDate()));//需求日期
				 orderBomExcel.setPmdb031(OrderBomUtils.setStringIfNotNull(CommonMst.ORDER_BOM.REASON_CODE));//默认值

				 String rawMaterialsAndAccessories = orderBom.getRawMaterialsAndAccessories();
				 if (StringUtils.hasLength(rawMaterialsAndAccessories) && CommonMst.ORDER_BOM.PARTS.equals(rawMaterialsAndAccessories)){//配件
					 orderBomExcel.setPmdb050(OrderBomUtils.setStringIfNotNull(orderBom.getPurchaseRequisitionRemarks()));//订购BOM中的"请购备注"
				 }else {//为空或原材料
					 orderBomExcel.setPmdb050(OrderBomUtils.setStringIfNotNull(orderBom.getSpecificationsDescription()));//订购BOM中的"规格说明"
				 }
				 orderBomExcel.setPmdb033(CommonMst.ORDER_BOM.URGENCY);//紧急度
				 orderBomExcel.setPmdbud003(OrderBomUtils.setStringIfNotNull(orderBom.getPartsType()));//订购BOM中的"部位编号/零件名"
				 orderBomExcel.setPmdbua001(OrderBomUtils.setStringIfNotNull(orderBom.getDesignNum()));//订购BOM中的"数量"
				 orderBomExcel.setPmdbud001(OrderBomUtils.setStringIfNotNull(orderBom.getT100MoldNo()));//订购BOM中的"T100模具编码"
				 orderBomExcels.add(orderBomExcel);
			 }
		 }
		 //组装要导出的数据
		 orderBomExcelArrayList.addAll(orderBomExcels);
		 return orderBomExcelArrayList;
	 }








	 /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("ch_order_bom:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ChOrderBom.class);
    }




}


